YAHOO.util.Event.onContentReady("scaffold-button", function () {
	
	YAHOO.util.Event.on(YAHOO.util.Dom.get('scaffold-button'), "click", function () { 
		var retry_count = 0;
		var RequestScaffoldProjectGeneration = {
			handleSuccess:function (o) {
					wait_dialog.hide(); 
					try {
						var tempArr = YAHOO.lang.JSON.parse(o.responseText);
						alert("Result: " + tempArr[0]["result"] + "\n" + "Message: " +tempArr[0]["message"]+ "\n" + "Detail: " +tempArr[0]["detail"]);
						
						YAHOO.util.Dom.get('stacktrace').innerHTML = "";
						for (obj in tempArr[0]["stacktrace"]) {
							YAHOO.util.Dom.get('stacktrace').innerHTML += tempArr[0]["stacktrace"][obj] + "\n";
						}
					}
					catch(err) {
						alert("Error occurred while parsing incoming JSON data from server. Please check incoming JSON for inconsistencies");
						//YAHOO.util.Dom.get('stacktrace').innerHTML += err.message + "\n\r";
						YAHOO.util.Dom.get('stacktrace').innerHTML += o.responseText;
					}
				},
				handleFailure:function (o) {
					retry_count++;
					
					if (retry_count < 3) {
							RequestScaffoldProjectGeneration.startRequest();
					}
					else {
						wait_dialog.hide(); 
						YAHOO.util.Dom.get('stacktrace').innerHTML += o.responseText;
						alert('There was an error in processing your request. ' +
							'It is possible that the application was created, but the server response was delayed.\n' +
							'Check the folder structure to see if the files were generated and refer to the log file in "./cfturbine/logs/error-log.html".\n' +
							'Log file will not be generated if this is not a real error. Otherwise, click the "Generate Scaffolding" button to retry.');
					}
					
				},
				processResult: function (o){
					wait_dialog.hide(); 
					alert ('result process');
				},
				startRequest:function () {
					wait_dialog.show();
					
					YAHOO.util.Connect.asyncRequest('POST','./generators/RunGenerator.cfm?method=scaffolding',callback_scafolding,
						'dsn_name='+YAHOO.util.Dom.get("dsn_name").value +
						'&context_name='+YAHOO.util.Dom.get("context_name").value +
						'&db_name='+db_env_button.get("value") +
						'&table_name='+YAHOO.util.Dom.get("table_name").value +
						'&model_name='+YAHOO.util.Dom.get("model_name").value +
						'&generated_sql='+YAHOO.util.Dom.get("generated_sql").value +
						'&generated_mdl='+YAHOO.util.Dom.get("generated_mdl").value +
						'&create_model='+!YAHOO.util.Dom.get('no_model').checked +
						'&create_views='+!YAHOO.util.Dom.get('no_view').checked +
						'&create_controller='+!YAHOO.util.Dom.get('no_controller').checked +
						'&create_dao='+!YAHOO.util.Dom.get('no_dao').checked +
						'&create_migrations='+!YAHOO.util.Dom.get('no_migrations').checked +
						'&create_service_proxy='+!YAHOO.util.Dom.get('no_service_proxy').checked +
						'&pretty_urls='+YAHOO.util.Dom.get('pretty_urls').checked);	
				}
			};
		var callback_scafolding = {
			success:RequestScaffoldProjectGeneration.handleSuccess,
			failure:RequestScaffoldProjectGeneration.handleFailure,
			scope:RequestScaffoldProjectGeneration,
			timeout: app_timeout 
		};
		
		RequestScaffoldProjectGeneration.startRequest();
	});
});	




YAHOO.util.Event.onContentReady("finalize-button", function () {	
	YAHOO.util.Event.on(YAHOO.util.Dom.get('finalize-button'), "click", function () { 
	
		if (YAHOO.util.Dom.get('dsn_name').value.length == 0 || YAHOO.util.Dom.get('context_name').value.length == 0) {
			alert ("Please provide a valid context/application name and datasource");
			return false;
		}
		
		if (document.getElementById('table_name').value.length > 0 && document.getElementById('model_name').value.length > 0 && tbl.getRecordSet()._records.length > 0) {
			// ----------------------------------------------------------------------------------------------------------------------
			var constraints = "";
			var pk_fields = [];
			var fk_fields = [];
			document.getElementById('generated_sql').innerHTML = "CREATE TABLE " + document.getElementById('table_name').value + "(\n";
			for (var i=0;i<tbl.getRecordSet()._records.length;i++) 
			{
				document.getElementById('generated_sql').innerHTML += (i > 0)?",\n":"";
				document.getElementById('generated_sql').innerHTML += "\t"+ tbl.getRecordSet()._records[i]._oData.db_field_name + " ";
				
				
				if (tbl.getRecordSet()._records[i]._oData.db_field_datatype == "datetime") {
					switch (db_env_button.get("value").toLowerCase())
					{
						case "sqlite":
							document.getElementById('generated_sql').innerHTML += " datetime";
						break;
						case "mysql":
							document.getElementById('generated_sql').innerHTML += " datetime";
						break;
						case "mssql":
							document.getElementById('generated_sql').innerHTML += tbl.getRecordSet()._records[i]._oData.db_field_datatype;
						break;
					}
				}
				else{
					document.getElementById('generated_sql').innerHTML += tbl.getRecordSet()._records[i]._oData.db_field_datatype + " ";	
				}
							
				document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_length)?"(" + tbl.getRecordSet()._records[i]._oData.db_field_length + ") ":" ";
				
				if (tbl.getRecordSet()._records[i]._oData.db_field_datatype == "datetime") {
					switch (db_env_button.get("value").toLowerCase())
					{
						case "sqlite":
							document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_default)?"default " + tbl.getRecordSet()._records[i]._oData.db_field_default + " ":" ";
						break;
						case "mysql":
						break;
						case "mssql":
							document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_default)?"default " + tbl.getRecordSet()._records[i]._oData.db_field_default + " ":" ";
						break;
					}
				}
				else{
					if (tbl.getRecordSet()._records[i]._oData.db_field_datatype=="bit"){
						document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_default)?"default 1" + " ":" ";
					}	
					else if	(tbl.getRecordSet()._records[i]._oData.db_field_datatype == "integer"){
						
						document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_default)?"default " + tbl.getRecordSet()._records[i]._oData.db_field_default + " ":" ";	
					}
					else{
						document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_default)?"default '" + tbl.getRecordSet()._records[i]._oData.db_field_default + "' ":" ";
					}
				}
				
				document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_isPrimaryKey)? "primary key ":" ";
				
				if (tbl.getRecordSet()._records[i]._oData.db_field_isPrimaryKey) {
					pk_fields.push(tbl.getRecordSet()._records[i]._oData.db_field_name)
				}
				
				//alert (db_env_button.get("value").toLowerCase());
				switch (db_env_button.get("value").toLowerCase())
				{
					case "sqlite":
						document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_isIdentity)? "autoincrement ":" ";
					break;
					case "mysql":
						document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_isIdentity)? "auto_increment ":" ";
					break;
					case "mssql":
						document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_isIdentity)? "identity ":" ";
					break;
				}
				
				
				if (tbl.getRecordSet()._records[i]._oData.db_field_datatype != "text") {
					document.getElementById('generated_sql').innerHTML += (tbl.getRecordSet()._records[i]._oData.db_field_allowNull)?" ":"not null";
				}
				
				if (tbl.getRecordSet()._records[i]._oData.db_field_isForeignKey == true) {
					constraints += ",\n"
					constraints += " constraint " + tbl.getRecordSet()._records[i]._oData.db_field_name + "_fk foreign key (";
					constraints += "" + tbl.getRecordSet()._records[i]._oData.db_field_name + ") references ";
					constraints += tbl.getRecordSet()._records[i]._oData.db_field_refers_table + "(";
					constraints += tbl.getRecordSet()._records[i]._oData.db_field_refers_column + ")";
					
					fk_fields.push(tbl.getRecordSet()._records[i]._oData.db_field_name);
				}
	
				if (tbl.getRecordSet()._records[i]._oData.db_field_isUnique == true) {
					constraints += "\t,\n"
					constraints += "\tconstraint unq_" + tbl.getRecordSet()._records[i]._oData.db_field_name + " unique (" + tbl.getRecordSet()._records[i]._oData.db_field_name + ")";
				}
				
				var field_key_name = "";
				for (j = 0;j<fk_fields.length;j++) {
					if (j == 0) {
						field_key_name = fk_fields[j];
					}
					else {
						field_key_name += "_" + fk_fields[j];
					}
				}
				
				if (pk_fields.length == 0 && fk_fields.length > 1) {
					constraints += "\t,\n";
					constraints += "\tconstraint pk_" + field_key_name + " primary key (" + fk_fields + ")";
				}
				
				
			}
			document.getElementById('generated_sql').innerHTML += constraints;
			document.getElementById('generated_sql').innerHTML += "\n)";
			// ----------------------------------------------------------------------------------------------------------------------
			// open model description
			document.getElementById('generated_mdl').innerHTML = '{"' + document.getElementById('model_name').value + '":{\n';
			for (var i=0;i<tbl.getRecordSet()._records.length;i++) {
				document.getElementById('generated_mdl').innerHTML += (i > 0)?',':'';
				document.getElementById('generated_mdl').innerHTML += '"' + tbl.getRecordSet()._records[i]._oData.db_field_name + '":{';
				// open field description
				
				if (!tbl.getRecordSet()._records[i]._oData.db_field_datatype || tbl.getRecordSet()._records[i]._oData.db_field_datatype.length == 0) {
					document.getElementById('generated_sql').innerHTML = '';
					document.getElementById('generated_mdl').innerHTML = '';
					alert ('You have not specified the data type for this column');
					return;
				}
				switch (tbl.getRecordSet()._records[i]._oData.db_field_datatype) {
					case 'varchar':
						document.getElementById('generated_mdl').innerHTML += '"type":"varchar"';
						if (!tbl.getRecordSet()._records[i]._oData.db_field_length || tbl.getRecordSet()._records[i]._oData.db_field_length.length == 0) {
							document.getElementById('generated_sql').innerHTML = '';
							document.getElementById('generated_mdl').innerHTML = '';
							alert ('You have not specified the length property for this field');
							return;
						}
					break;
					case 'integer':
						document.getElementById('generated_mdl').innerHTML += '"type":"integer"';
					break;
					case 'decimal':
						document.getElementById('generated_mdl').innerHTML += '"type":"decimal"';
						if (!tbl.getRecordSet()._records[i]._oData.db_field_length || tbl.getRecordSet()._records[i]._oData.db_field_length.length == 0) {
							document.getElementById('generated_sql').innerHTML = '';
							document.getElementById('generated_mdl').innerHTML = '';
							alert ('You have not specified the length property for this field');
							return;
						}
					break;
					case 'bit':
						document.getElementById('generated_mdl').innerHTML += '"type":"bit"';
					break;
					case 'datetime':
						document.getElementById('generated_mdl').innerHTML += '"type":"timestamp"';
					break;
					case 'text':
						document.getElementById('generated_mdl').innerHTML += '"type":"longvarchar"';
					break;
				}
				
				
				if (tbl.getRecordSet()._records[i]._oData.db_field_length && tbl.getRecordSet()._records[i]._oData.db_field_length.length > 0){
					if (tbl.getRecordSet()._records[i]._oData.db_field_length.split(',').length > 1) {
						document.getElementById('generated_mdl').innerHTML += ',"maxlength":' + (parseInt(tbl.getRecordSet()._records[i]._oData.db_field_length.split(',')[0]) + parseInt(tbl.getRecordSet()._records[i]._oData.db_field_length.split(',')[1])) ;
					}
					else {
						document.getElementById('generated_mdl').innerHTML += ',"maxlength":' + tbl.getRecordSet()._records[i]._oData.db_field_length;
					}
				}
				
				document.getElementById('generated_mdl').innerHTML += ',"default":"' + tbl.getRecordSet()._records[i]._oData.db_field_default + '"';
				
				if (tbl.getRecordSet()._records[i]._oData.db_field_isPrimaryKey){
					document.getElementById('generated_mdl').innerHTML += ',"key":"primary"';
					
					
					
					if (tbl.getRecordSet()._records[i]._oData.db_field_isIdentity){
						document.getElementById('generated_mdl').innerHTML += ',"identity":' + true;
					}
					
				}
				else if (tbl.getRecordSet()._records[i]._oData.db_field_isForeignKey) {
					document.getElementById('generated_mdl').innerHTML += ',"key":"foreign"';
					document.getElementById('generated_mdl').innerHTML += ',"references":"' + tbl.getRecordSet()._records[i]._oData.db_field_refers_table  + '.' + tbl.getRecordSet()._records[i]._oData.db_field_refers_column +'"';
					
					if (!(tbl.getRecordSet()._records[i]._oData.db_field_refers_table.length > 0) || !(tbl.getRecordSet()._records[i]._oData.db_field_refers_column.length > 0)){
						document.getElementById('generated_sql').innerHTML = '';
						document.getElementById('generated_mdl').innerHTML = '';
						alert ('You have not specified the foreign key references.');
						return;	
					}
					
				}	
				if (tbl.getRecordSet()._records[i]._oData.db_field_datatype != "text"){
					
					document.getElementById('generated_mdl').innerHTML += ',"required":' + !(tbl.getRecordSet()._records[i]._oData.db_field_allowNull);
				} else {
					alert ("The datatype youve selected is 'text'. Allow Nulls preference will be ignored");
				}
				document.getElementById('generated_mdl').innerHTML += ',"unique":' + tbl.getRecordSet()._records[i]._oData.db_field_isUnique;
				
				if (!tbl.getRecordSet()._records[i]._oData.db_field_mapping || tbl.getRecordSet()._records[i]._oData.db_field_mapping.length == 0) {
					document.getElementById('generated_mdl').innerHTML += ',"mapping":"' + tbl.getRecordSet()._records[i]._oData.db_field_name + '"';
					if (tbl.getRecordSet()._records[i]._oData.db_field_isForeignKey) {
						document.getElementById('generated_mdl').innerHTML += ',"mapping":"' + tbl.getRecordSet()._records[i]._oData.db_field_refers_column + '"';
					}
				}
				else {
					document.getElementById('generated_mdl').innerHTML += ',"mapping":"' + tbl.getRecordSet()._records[i]._oData.db_field_mapping + '"';
				}
				
				document.getElementById('generated_mdl').innerHTML += ',"value":""';
				document.getElementById('generated_mdl').innerHTML += '}';
			}
			document.getElementById('generated_mdl').innerHTML += '}}';
		}
		else {
			alert ('Table or model name is not specified or Datatable is not properly defined');
		}


		if ((YAHOO.util.Dom.get('model_name').value.length > 0) || (YAHOO.util.Dom.get('table_name').value.length > 0)) {
			Submit_Button.set("disabled", false);		
		}
	});
});